package me.zhengjie.modules.system.service.mapstruct.convertor.impl;

import lombok.RequiredArgsConstructor;
import me.zhengjie.config.MappingProperties;
import me.zhengjie.modules.system.domain.System;
import me.zhengjie.modules.system.repository.SystemRepository;
import me.zhengjie.modules.system.service.mapstruct.convertor.SerialNoConvertor;
import me.zhengjie.utils.StringUtils;
import org.mapstruct.Named;
import org.springframework.stereotype.Component;

/**
 * SystemConvertor
 *
 * @author guoyuan
 * @version 1.0.0
 * @since 1.0.0
 */
@Component
@RequiredArgsConstructor
@Named("systemConvertor")
public class SystemConvertor implements SerialNoConvertor {

    private static final String SPLIT = "-";
    private final SystemRepository systemRepository;
    private final MappingProperties mappingProperties;

    /**
     * 对象转json字符串
     *
     * @param systemName /
     * @return /
     */
    @Named("systemNamePenetrate")
    public String systemNamePenetrate(String systemName) {
        return systemName;
    }

    @Named("systemId2Integer")
    public Integer systemId2Integer(String systemId) {
        if (StringUtils.isBlank(systemId)) {
            return null;
        }
        final int i = systemId.lastIndexOf(SPLIT) + 1;
        final String strDocNum = systemId.substring(i);
        return Integer.parseInt(strDocNum);
    }

    @Named("systemId2String")
    public String systemId2String(Integer systemId) {
        final System first = systemRepository.findFirstByOrderBySystemIdDesc();
        final String prefix = mappingProperties.getSystemNumPrefix() + SPLIT;
        final Integer zeroLen = mappingProperties.getSystemNumZeroLen();
        String strSystemId;
        if (first != null) {
            strSystemId = buildSerialNo(systemId, prefix, zeroLen, first.getSystemId());
        } else {
            strSystemId = prefix + systemId;
        }
        return strSystemId;
    }

}
